package com.example.a_java.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.Result;
import com.example.a_java.entity.SysUser;
import com.example.a_java.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Tag(name = "用户管理", description = "用户管理相关接口")
@RestController
@RequestMapping("/system/user")
@SecurityRequirement(name = "bearer-key")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @Operation(summary = "获取用户列表", description = "分页获取用户列表，支持多条件筛选")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('system:user:list')")
    public Result<Page<SysUser>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "真实姓名") @RequestParam(required = false) String realName,
            @Parameter(description = "手机号") @RequestParam(required = false) String mobile,
            @Parameter(description = "状态(0:禁用 1:正常)") @RequestParam(required = false) Integer status,
            @Parameter(description = "部门ID") @RequestParam(required = false) Long deptId,
            @Parameter(description = "角色ID") @RequestParam(required = false) Long roleId) {
        
        // 使用分页构造器
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        
        // 如果没有指定角色ID，使用基本条件查询
        if (roleId == null) {
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<SysUser>()
                    .like(StringUtils.hasText(username), SysUser::getUsername, username)
                    .like(StringUtils.hasText(realName), SysUser::getRealName, realName)
                    .eq(StringUtils.hasText(mobile), SysUser::getMobile, mobile)
                    .eq(status != null, SysUser::getStatus, status)
                    .eq(deptId != null, SysUser::getDeptId, deptId);
            
            userService.page(page, wrapper);
        } else {
            // 如果指定了角色ID，则需要通过角色ID查询关联的用户
            userService.getUsersByRoleId(page, roleId, username, status, deptId);
        }
        
        return Result.success(page);
    }

    @Operation(summary = "新增用户")
    @PostMapping
    @PreAuthorize("hasAuthority('system:user:add')")
    public Result<Boolean> add(@RequestBody @Valid SysUser user) {
        return Result.success(userService.save(user));
    }

    @Operation(summary = "修改用户")
    @PutMapping
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result<Boolean> update(@RequestBody @Valid SysUser user) {
        return Result.success(userService.updateById(user));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasAuthority('system:user:delete')")
    public Result<Boolean> delete(@PathVariable Long userId) {
        return Result.success(userService.removeById(userId));
    }

    @Operation(summary = "重置密码")
    @PutMapping("/resetPwd")
    @PreAuthorize("hasAuthority('system:user:resetPwd')")
    public Result<Boolean> resetPwd(@RequestBody SysUser user) {
        return Result.success(userService.resetUserPwd(user.getUserId(), user.getPassword()));
    }

    @Operation(summary = "获取用户详情")
    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('system:user:query')")
    public Result<SysUser> getInfo(@PathVariable Long userId) {
        return Result.success(userService.getById(userId));
    }
} 
